package kt.com.bilin.coin.ui.fragment

import android.app.Activity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.ViewCompat
import com.bilin.coin.ApiConstant
import com.bilin.coin.R
import com.bilin.coin.bean.CommonSuccessEvent
import com.bilin.coin.databinding.ItemHomeFun2Binding
import com.bilin.coin.databinding.ItemHomeFunctionBinding
import com.bilin.coin.network.RetrofitConfig
import com.bilin.coin.tools.AlertUtils
import com.bilin.coin.utils.DateUtil
import com.bilin.coin.utils.MoneyUtils
import com.bumptech.glide.Glide
import com.youth.banner.BannerConfig
import kotlinx.android.synthetic.main.fragment_v2_home.*
import kt.com.bilin.coin.ad.AdManager.loadRewardVideoAd
import kt.com.bilin.coin.api.API_SERVICE
import kt.com.bilin.coin.api.ApiObserver
import kt.com.bilin.coin.api.toData
import kt.com.bilin.coin.bean.*
import kt.com.bilin.coin.common.*
import kt.com.bilin.coin.helper.newInstance
import kt.com.bilin.coin.ui.activity.MainActivity
import kt.com.bilin.coin.ui.adapter.BaseRecyclerAdapter
import kt.com.bilin.coin.ui.adapter.BaseViewHolder
import kt.com.bilin.coin.utils.FullyGridLayoutManager
import kt.com.bilin.coin.utils.GlideImageLoader
import kt.com.bilin.coin.utils.KotlinTransferJava
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal

class HomeFragment : BaseFragment(R.layout.fragment_v2_home) {
    private val mHomeFunctionAdapter: HomeFunctionAdapter = HomeFunctionAdapter()
    private val mHomeFun2Adapter: HomeFun2Adapter = HomeFun2Adapter()
    private lateinit var mMarqueeMessages: MutableList<AnnounceBean>
    private lateinit var mBanners: MutableList<BannerBean>
    private var tempHadAmount: Double? = null
    private var timer: CountDownTimer? = null
    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        bindViewClick(this, llGoldBean, llSeed, llJixiao, llPoints, tvMoreAnnouncement)
        refreshLayout.setOnRefreshListener { onRefresh() }
        refreshLayout.setEnableLoadMore(false)
        mHomeFunctionAdapter.datas = mutableListOf<HomeFunctionBean>().apply {
            add(HomeFunctionBean(R.mipmap.icon_home_huafei, R.string.text_home_prepaid_refill.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_jiayou, R.string.text_home_gas.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_gyi, R.string.text_home_public_welfare.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_liliang, R.string.text_home_flow_recharge.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_game, R.string.text_home_entertainment_recharge.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_card, R.string.text_home_credit_card.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_airport, R.string.text_home_plane_ticket.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_hotel, R.string.text_home_hotel.getString()))
        }
        mHomeFunctionAdapter.setOnClickAdapterListenter(::onClickLifeService)
        rvFunction.layoutManager = FullyGridLayoutManager(requireContext(), 4)
        rvFunction.adapter = mHomeFunctionAdapter
        mHomeFun2Adapter.datas = mutableListOf<HomeFunctionBean>().apply {
            add(HomeFunctionBean(R.mipmap.icon_home_team, R.string.text_home_my_team.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_kji, R.string.text_home_my_mill.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_bil, R.string.text_home_lucky.getString()))
            add(HomeFunctionBean(R.mipmap.icon_home_xuey, R.string.text_home_business_school.getString()))
        }
        mHomeFun2Adapter.setOnClickAdapterListenter(::onClickFun2)
        rvFun2.layoutManager = FullyGridLayoutManager(requireContext(), 4)
        rvFun2.adapter = mHomeFun2Adapter
        marqueeView.setOnItemClickListener(::marqueeClick)
    }

    override fun initData(rootView: View?, savedInstanceState: Bundle?) {
        mBanners = mutableListOf<BannerBean>().apply {
            add(BannerBean(id = R.mipmap.banner_1))
            add(BannerBean(id = R.mipmap.banner_2))
            add(BannerBean(id = R.mipmap.banner_3))
            add(BannerBean(id = R.mipmap.banner_4, jumpUrl = "chongzhi"))
            add(BannerBean(id = R.mipmap.banner_5, jumpUrl = "choujiang"))
        }
        val cover = mutableListOf<Int>().apply { mBanners.forEach { add(it.id) } }
        banner.run {
            setImageLoader(GlideImageLoader())
            setIndicatorGravity(BannerConfig.RIGHT)
            setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
            setOnBannerListener {
                when (mBanners[it].jumpUrl) {
                    "chongzhi" -> handRvClick(R.mipmap.icon_home_huafei)
                    "choujiang" -> handRvClick(R.mipmap.icon_home_bil)
                }
            }
            setDelayTime(5000)
            setImages(cover)
        }.start()
        onRefresh()
    }

    private fun onClickLifeService(v: View, position: Int) {
        handRvClick(mHomeFunctionAdapter.datas[position].icon)
    }

    private fun onClickFun2(v: View, position: Int) {
        handRvClick(mHomeFun2Adapter.datas[position].icon)
    }

    private fun handRvClick(icon: Int) {
        when (icon) {
//            R.mipmap.icon_home_huafei -> ARouterNavigation(PATH_PREPAID_REFILL)
            R.mipmap.icon_home_jiayou -> ARouterNavigation("/common/WebPageLoading") {
                withString("url", "https://open.czb365.com/redirection/todo?platformType=92652715&platformCode=18210016397")
                withString("title", "加油")
                withString("menuName", "视频教程")
                withString("menuUrl", MP4_2)
                withBoolean("isVideo", true)
            }
            R.mipmap.icon_home_gyi -> ARouterNavigation(PATH_PUBLIC_WELFARE)
            R.mipmap.icon_home_huafei,
            R.mipmap.icon_home_liliang,
            R.mipmap.icon_home_game,
            R.mipmap.icon_home_card,
            R.mipmap.icon_home_airport,
            R.mipmap.icon_home_hotel,
            -> AlertUtils.dialog(requireActivity()) {}
            R.mipmap.icon_home_team -> ARouterNavigation("/auction/MyTeamActivity")
            R.mipmap.icon_home_kji -> ARouterNavigation(PATH_Mill)
            R.mipmap.icon_home_bil -> ARouterNavigation(PATH_LUCKY_TURNTABLE)
            R.mipmap.icon_home_xuey -> ARouterNavigation(PATH_BUSINESS_SCHOOL)
        }
    }

    override fun onClick(v: View?) {
        when (v) {
//            ivInvite -> ARouterNavigation("/auction/InviteActivity")
            llGoldBean -> ARouterNavigation("/auction/GoldBeanDetailActivity")
            llSeed -> ARouterNavigation("/auction/SeedDetailActivity")
            llJixiao -> ARouterNavigation("/auction/JiXiaoDetailActivity")
            llPoints -> ARouterNavigation("/auction/PointDetailActivity")
            tvMoreAnnouncement -> ARouterNavigation("/mall/NewsListActivity")
        }
    }

    private fun onRefresh() {
        launchUI({
            handData(
                    //API_SERVICE.banner().toData(),
                    API_SERVICE.announce().toData()?.records,
                    API_SERVICE.getMoney().toData(),
                    API_SERVICE.getStatus().toData(),
            )
        }, ApiObserver(context, refreshLayout = refreshLayout))
    }

    //banners: MutableList<BannerBean>?,
    private fun handData(announces: MutableList<AnnounceBean>?, money: MoneyBean?, digStatus: DigStatusBean?) {
        announces?.also {
            mMarqueeMessages = it
            KotlinTransferJava.marqueeViewStartWithList(marqueeView, it)
        }
        handMoney(money)
        handDigStatus(digStatus)
    }

    private fun marqueeClick(position: Int, textView: TextView) {
        ARouterNavigation("/common/WebPageLoading") {
            withString("url", RetrofitConfig.newsUrl + mMarqueeMessages[position].id)
            withString("title", "公告详情")
        }
    }

    private fun handMoney(money: MoneyBean?) {
        money?.also {
            tvGold.text = it.jd.formatDouble()
            tvSeed.text = it.zz.formatDouble()
            tvPoint.text = it.gf.formatDouble()
            tvJx.text = it.jx.formatDouble()
//            tvGold.text = "11684.40"
//            tvSeed.text = "291930.40"
//            tvPoint.text = "630.40"
//            tvJx.text = "63874.000000"
        }
    }

    private fun handDigStatus(digStatusBean: DigStatusBean?) {
        digStatusBean?.run {
            tempHadAmount = MoneyUtils.decimal2ByUp2(BigDecimal(hadAmount)).toDouble()
            tvGenAmount.text = "已产出 $tempHadAmount"
            // 0-在挖 1-待收 2-已收(今日可挖) 3-已收（今日不可挖）
            when (digStatus) {
                "0" -> {
                    timer?.cancel()
                    tvTimeOrDig.text = "剩余:$remainSecond"
                    ViewCompat.setBackground(tvTimeOrDig, R.drawable.bg_mining_in.getDrawable())
                    tvTimeOrDig.setTextColor(R.color.main_color.toColor())
                    tvTimeOrDig.isClickable = false
                    Glide.with(requireContext()).asGif().load(R.mipmap.mill_dt).into(ivMill)
                    if (canSpeed) {
                        ivSpeed.setOnClickListener {
                            loadRewardVideoAd(activity) {
                                launchUI({
                                    API_SERVICE.lookVideo().toData()
                                    handDigStatus(API_SERVICE.getStatus().toData())
                                }, ApiObserver(context))
                            }
                        }
                    } else {
                        ivSpeed.setOnClickListener { "今日已加速，每日只可加速一次".toastMessageLong() }
                    }
                    timer = object : CountDownTimer(remainSecond.toLong() * 1000, 1000) {
                        override fun onTick(millisUntilFinished: Long) {
                            tvTimeOrDig.text = "${DateUtil.getDiffDDHHMMSS(millisUntilFinished.toString())}"
                            tempHadAmount?.also {
                                tempHadAmount = it + jdPerSecond.toDouble()
                                tvGenAmount.text = "已产出 " + MoneyUtils.decimal8ByUp(BigDecimal(tempHadAmount!!))
                            }
                        }

                        override fun onFinish() {
                            if (remainSecond.toLong() > 0) {
                                Handler().postDelayed({ launchUI({ handDigStatus(API_SERVICE.getStatus().toData()) }, ApiObserver(context)) }, 5000)
                            }
                        }
                    }.start()
                }
                "1" -> {
                    timer?.cancel()
                    ivSpeed.setOnClickListener { "您今日已完成挖矿，不可进行加速".toastMessageLong() }
                    ViewCompat.setBackground(tvTimeOrDig, R.drawable.bg_mining_receive.getDrawable())
                    tvTimeOrDig.setTextColor(R.color.white.toColor())
                    tvTimeOrDig.text = "领取金豆"
                    tvTimeOrDig.isClickable = true
                    tvTimeOrDig.setOnClickListener {
                        launchUI({
                            API_SERVICE.cat().toData()
                            handMoney(API_SERVICE.getMoney().toData())
                            handDigStatus(API_SERVICE.getStatus().toData())
                        }, ApiObserver(context))
                    }
                    ivMill.setImageResource(R.mipmap.mill_dt)
                }
                "2" -> {
                    timer?.cancel()
                    tvGenAmount.text = "矿机暂未开启"
                    ivSpeed.setOnClickListener { "您还未开始挖矿，不可进行加速".toastMessageLong() }
                    ViewCompat.setBackground(tvTimeOrDig, R.drawable.bg_mining_default.getDrawable())
                    tvTimeOrDig.text = "开始挖矿"
                    tvTimeOrDig.setTextColor(R.color.white.toColor())
                    tvTimeOrDig.isClickable = true
                    tvTimeOrDig.setOnClickListener {
                        launchUI({
                            API_SERVICE.dig().toData()
                            handDigStatus(API_SERVICE.getStatus().toData())
                        }, ApiObserver(context))
                    }
                    ivMill.setImageResource(R.mipmap.mill_dt)
                }
                "3" -> {
                    timer?.cancel()
                    tvGenAmount.text = "已完成挖矿"
                    ivSpeed.setOnClickListener { "您今日已完成挖矿，不可进行加速".toastMessageLong() }
                    ViewCompat.setBackground(tvTimeOrDig, R.drawable.bg_mining_default.getDrawable())
                    tvTimeOrDig.setTextColor(R.color.white.toColor())
                    tvTimeOrDig.text = "已领取"
                    tvTimeOrDig.isClickable = false
                    ivMill.setImageResource(R.mipmap.mill_dt)
                }
            }
            Unit
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.LoginSuccess) {
            onRefresh()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun logoutSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.LogoutSuccess) {
            onRefresh()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            marqueeView.stopFlipping()
        } else {
            marqueeView.startFlipping();
        }
    }

    override fun onStart() {
        super.onStart()
        marqueeView.startFlipping();
    }

    override fun onStop() {
        super.onStop()
        marqueeView.stopFlipping()
    }
}

class HomeFunctionAdapter : BaseRecyclerAdapter<BaseViewHolder<ItemHomeFunctionBinding>, HomeFunctionBean>() {
    override fun onCreateViewHolder(parent: ViewGroup, p1: Int) = BaseViewHolder(ItemHomeFunctionBinding.inflate(getLayoutInflate(parent.context), parent, false))
    override fun onBindViewHolder(holder: BaseViewHolder<ItemHomeFunctionBinding>, bean: HomeFunctionBean, position: Int) {
        holder.mViewBinding.run {
            bean.run {
                ivIcon.setImageResource(icon)
                tvName.text = name
                setViewClick(position, root)
            }
        }
    }
}

class HomeFun2Adapter : BaseRecyclerAdapter<BaseViewHolder<ItemHomeFun2Binding>, HomeFunctionBean>() {
    override fun onCreateViewHolder(parent: ViewGroup, p1: Int) = BaseViewHolder(ItemHomeFun2Binding.inflate(getLayoutInflate(parent.context), parent, false))
    override fun onBindViewHolder(holder: BaseViewHolder<ItemHomeFun2Binding>, bean: HomeFunctionBean, position: Int) {
        holder.mViewBinding.run {
            bean.run {
                ivIcon.setImageResource(icon)
                tvName.text = name
                setViewClick(position, root)
            }
        }
    }
}